import router, { asyncRoutes, constantRoutes } from 'admin/router'
import api from 'admin/api'
import utils from 'admin/utils/utils'
import store from 'admin/store'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
    if (route.meta && route.meta.roles) {
        return roles.some((role) => route.meta.roles.includes(role))
    } else {
        return true
    }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
    const res = []

    routes.forEach((route) => {
        const tmp = { ...route }
        if (hasPermission(roles, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, roles)
            }
            res.push(tmp)
        }
    })

    return res
}

const state = {
    routes: [],
    addRoutes: [],
    btns: []
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes
        state.routes = [...constantRoutes.concat(routes), { path: '*', redirect: '/404', hidden: true }]
    },
    SET_BTNS: (state, btns) => {
        state.btns = btns
    }
}

const actions = {
    // 获取挂载router
    async generateRoutes({ commit, dispatch }) {
        // const newRoutes = await dispatch('getMenuPermission')
        // console.log('newRoutes', newRoutes)
        // console.log('asyncRoutes', asyncRoutes)
        // commit('SET_ROUTES', newRoutes)
        // router.addRoutes(newRoutes)
        // console.log('asyncRoutes',...asyncRoutes)
        commit('SET_ROUTES', asyncRoutes)
        router.addRoutes(asyncRoutes)
    },
    async getMenuPermission({state, commit, dispatch }) {
        dispatch('getBtnPermission')
        // 查找router
        let currentRouter = {}

        function findRouter(route = [], mark) {
            route.forEach((item) => {
                if (item.name === mark) {
                    currentRouter = item
                }
                if (item.children && item.children.length) {
                    findRouter(item.children, mark)
                }
            })
            return currentRouter
        }

        // 递归
        function recursiveRouter(routers) {
            routers.forEach((item) => {
                let existRouter = findRouter(asyncRoutes, item.mark)
                currentRouter = {}
                item.path = item.route
                item.meta = {}
                item.meta.title = item.name
                // 添加按钮配置
                item.meta.icon = item.icon
                item.component = existRouter.component
                item.name = item.mark
                    
                delete item.order
                delete item.parentId
                delete item.parentName
                delete item.route
                delete item.type
                delete item.alias
                delete item.mark
                // delete item.id
                if (!item.children) delete item.children
                // console.log('item', item)
                // existRouter
                if (item.children && item.children.length) {
                    item.alwaysShow = true
                    recursiveRouter(item.children)
                }
            })

            return routers
        }

        // 查找对应页面的按钮
        function findRouterBtns(id) {
            return state.btns.filter(v=> v.parentId === id)
        }

        const { data, code } = await api.user.getMenuPermission()
        if (code === 200) {
            return recursiveRouter(data)
        }
        return []
    },

    // 请求按钮
    async getBtnPermission({ state, commit }) {
        const { data, code } = await api.user.getBtnPermission()
        if (code === 200) {
            commit('SET_BTNS', data.map(v=> v.mark))
        }
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
}
